﻿using HsServerHa.Utility.NetWork;
using System;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace HsServerHa
{
    public static class TCPServerHelper
    {
        public static CancellationToken token;

        public static IPEndPoint iPEndPoint;
        #region  服务端通信
        /// <summary>
        /// 发起心跳TCP
        /// </summary>
        /// <returns></returns>
        public static bool InitiateHeart(CancellationToken tokens, Socket socketServer, string XtIP)
        {
            try
            {
                if (XtIP == null)
                {
                    return false;
                }
                token = tokens;  
                if (NetWorkHelper.ValidateIpAddress(XtIP))
                {
                    if (socketServer == null)
                    {
                        TcpListener server = new TcpListener(IPAddress.Parse(XtIP), int.Parse(ConfigurationManager.AppSettings["HeartPort"]?.ToString() ?? "6600"));
                        server.Start();
                        socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        App.socketServer = socketServer;
                        App.proxSocket = socketServer;
                        socketServer = server.AcceptSocket();

                        //socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        //iPEndPoint = new IPEndPoint(IPAddress.Parse(XtIP), int.Parse(ConfigurationManager.AppSettings["HeartPort"]?.ToString() ?? "6600"));
                        //socketServer.Bind(iPEndPoint);
                        //socketServer.Listen(1);
                        App.socketServer = socketServer;
                        App.proxSocket = socketServer;
                        NetworkStream stream = new NetworkStream(socketServer);

                        byte[] data = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = stream.Read(data, 0, data.Length)) != 0)
                        {
                            //string message = Encoding.ASCII.GetString(data, 0, bytesRead);
                            //Console.WriteLine("Received: " + message);

                            if (Encoding.ASCII.GetString(data, 0, bytesRead) == "1")
                            {
                                App.XtIsOpen = true;
                                // 回复心跳包
                                //byte[] heartbeatData = Encoding.ASCII.GetBytes("1");
                                stream.Write(App.sendData, 0, App.sendData.Length);
                            }
                          
                        }

                        //ThreadPool.QueueUserWorkItem(new WaitCallback(AcceptClientConnect), socketServer);
                        //LoggerHelper.Info("创建成功", "创建心跳服务");
                        return true;
                    }
                }

            }
            catch (Exception ex)
            {
                socketServer.Dispose();
                LoggerHelper.Error($"创建失败：{ex.Message}", "创建心跳服务");
            }
            return false;
        }

        /// <summary>
        /// 线程池线程执行的接受客户端连接方法
        /// </summary>
        /// <param name="obj">传入的Socket</param>

        private static void AcceptClientConnect(object obj)
        {
            //转换Socket
            var serverSocket = obj as Socket;
            //不断接受客户端的连接
            while (!token.IsCancellationRequested)
            {
                //5、创建一个负责通信的Socket
                App.proxSocket = serverSocket.Accept();
                //将连接的Socket存入集合

                //6、不断接收客户端发送来的消息
                ThreadPool.QueueUserWorkItem(new WaitCallback(ReceiveClientMsg), App.proxSocket);

            }

        }


     
        /// <summary>
        /// 不断接收客户端信息子线程方法
        /// </summary>
        /// <param name="obj">参数Socke对象</param>
        private static void ReceiveClientMsg(object obj)
        {
            var proxSocket = obj as Socket;
            //创建缓存内存，存储接收的信息   ,不能放到while中，这块内存可以循环利用
            while (!token.IsCancellationRequested)
            {
                //int len;
                try
                {
                    //接收消息,返回字节长度
                   /* len =*/
                    proxSocket.Receive(App.acceptData);
                    //if (len > 0)
                    //{
                    //    App.proxSocket=proxSocket;
                    //    App.socketServer = proxSocket;
                    //}
                }
                catch (Exception ex)
                {
                    App.acceptData = null;
                    App.acceptData = new byte[1 * 1024];
                    LoggerHelper.Error(ex.Message);
                }


                //将消息显示到TxtLog

                //string msgStr = Encoding.Default.GetString(data, 0, len);
            
                //拼接字符串

                //LoggerHelper.Info(string.Format("接收到客户端：{0}的消息：{1}", proxSocket.RemoteEndPoint.ToString(), msgStr));

            }
        }
        #endregion
    }
}
